package com.github.redis.service.impl;

import com.github.redis.entity.User;
import com.github.redis.mapper.UserMapper;
import com.github.redis.service.UserService;
import com.github.redis.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author gcq
 * @Create 2022-06-13
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private static final String CACHE_KEY_USER = "user:";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void createUser(User user) {
        this.userMapper.insert(user);

        String key = CACHE_KEY_USER + user.getId();
        User dbUser = this.userMapper.selectByPrimaryKey(user.getId());
        redisTemplate.opsForValue().set(key, dbUser);
    }

    @Override
    public User findUserById(int id) {
        String key = CACHE_KEY_USER + id;
        ValueOperations<String, User> valueOperations = redisTemplate.opsForValue();
        User user = valueOperations.get(key);
        if(user == null) {
            user = userMapper.selectByPrimaryKey(id);
            valueOperations.set(key, user);
        }
        return user;
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);

        String key = CACHE_KEY_USER + user.getId();
        user = userMapper.selectByPrimaryKey(user.getId());
        redisTemplate.opsForValue().set(key, user);
    }
}